#if 0
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>
#include <string>
#include <cstring>
#include <stdio.h>
#include <dirent.h>
#include "LinkTree.h"

using namespace std;

// 扫描文件夹
void ExploreDirectory(const std::string &path, TreeNode *node)
{
    DIR *dir = opendir(path.c_str());
    if (dir == nullptr)
    {
        std::cout << "文件夹路径有误!:" << path << std::endl;
    }
    // 读取文件目录下的文件夹列表
    dirent *e = nullptr;
    while ((e = readdir(dir)) != nullptr)
    {
        if (std::string(e->d_name) == "." || std::string(e->d_name) == "..")
        {
            continue;
        }
        TreeNode *child = new TreeNode(e->d_name);
        child->Connect(node);
        if (e->d_type == DT_DIR)
        {
            ExploreDirectory(path + "/" + std::string(e->d_name), child);
        }
        else
        {
            if (strstr(e->d_name, "mp3") != NULL)
            {
                cout << "d_name:" << e->d_name << endl;
            }
        }
    }
    // 关闭目录流
    closedir(dir);
}

int main()
{
    /* 打开文件夹 */
    string path = "/home/zyc/267--2/267SystemCall/267-system-call/FileIO/music";

    LinkTree tree(path);

    ExploreDirectory(path, tree.GetRoot());

    return 0;
}
#endif

#if 1
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string>
#include <cstring>
#include <dirent.h>

using namespace std;

void ExploreDirectoryAndPrintMP3s(const std::string &path)
{
    DIR *dir = opendir(path.c_str());
    if (dir == nullptr)
    {
        perror("opendir error:");
        return;
    }

    struct dirent *e = nullptr;
    while ((e = readdir(dir)) != nullptr)
    {
        if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0)
        {
            continue;
        }

        if (strstr(e->d_name, ".mp3") != NULL)
        {
            cout << "d_name: " << e->d_name << endl; 
        }
        else
        {
            std::string fullPath = path + "/" + e->d_name;
            struct stat fileStat;
            if (stat(fullPath.c_str(), &fileStat) == -1)
            {
                perror("stat error:");
                continue;
            }

            if (S_ISDIR(fileStat.st_mode))
            {
                ExploreDirectoryAndPrintMP3s(fullPath);
            }
        }
    }

    closedir(dir);
}

int main()
{
    string path = "/home/zyc/267--2/267SystemCall/267-system-call/FileIO/music";

    ExploreDirectoryAndPrintMP3s(path);

    return 0;
}
#endif